package com.knowif.backend.controller;

import com.knowif.aliOSS.enumConfig.AliOSSConfig;
import com.knowif.aliOSS.service.AliyunFileUtil;
import com.knowif.system.model.RestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author ：Xh
 * @date ：Created in 2019/6/20 0020 21:15
 */
@RestController
@RequestMapping("/wechat")
public class FileUploadController {

    @Autowired
    AliyunFileUtil aliyunFileUtil;

    @Value("${OSS.config.file.defaultPath}")
    private String defaultImage;

    @PostMapping("/uploadFile")
    public RestBean<?> updateImage(@RequestParam("file") MultipartFile file){
        if(file == null || file.isEmpty()) {
            return RestBean.buildError("无法读取文件");
        }else{
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replaceAll("-", "");
            String fileName = uuid;
            String suffix ="."+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
            fileName = (fileName + suffix).toUpperCase();
            try {
                aliyunFileUtil.fileUpload(AliOSSConfig.ALIIMAGE_STUDENT.setFileName(fileName),file.getInputStream());
                return RestBean.buildSuccess(defaultImage+fileName);
            } catch (IOException e) {
                e.printStackTrace();
                return RestBean.buildError("系统异常");
            }
        }
    }

    @GetMapping("/testUploadFile")
    public void  testUploadFile(@RequestParam("path") String path){
        File parent = new File(path);
        File[] files = parent.listFiles();
        for (int i = 0; i < files.length; i++){
            File file = files[i];
            System.out.println(file.getPath());
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replaceAll("-", "");
            String fileName = uuid;
            String suffix ="."+ file.getPath().substring(file.getPath().lastIndexOf(".")+1);
            fileName = (fileName + suffix).toUpperCase();
            try {
                FileInputStream fis = new FileInputStream(file);
                aliyunFileUtil.fileUpload(AliOSSConfig.ALIIMAGE_STUDENT.setFileName(fileName),fis);
                System.out.println(file.getName() + " : " +defaultImage + fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
